package com.xiaoxin.experience.system.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 获取Spring上下文对象
 */
@Slf4j
@Component
public class ApplicationContextHolder implements ApplicationContextAware
{
    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext = null;

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
    {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     *
     * @return {@link ApplicationContext}
     */
    public static ApplicationContext getApplicationContext()
    {
        Assert.notNull(applicationContext, "application context not aware.");
        return applicationContext;
    }

    /**
     * 通过key获取属性值.
     *
     * @param key {@link String} key
     * @return {@link String}
     */
    public static String getProperty(String key)
    {
        return getApplicationContext().getEnvironment().getProperty(key);
    }

    /**
     * 通过key获取属性值，找不到返回默认值.
     *
     * @param key      {@link String} key
     * @param defValue {@link String} defValue
     * @return {@link String}
     */
    public static String getProperty(String key, String defValue)
    {
        return getApplicationContext().getEnvironment().getProperty(key, defValue);
    }

    /**
     * 通过class获取Bean.
     *
     * @param name {@link String}
     * @param <T>  type
     * @return {@link Object}
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name)
    {
        return (T)getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz {@link Class}
     * @param <T>   type
     * @return {@link Object}
     */
    public static <T> T getBean(Class<T> clazz)
    {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name  {@link String}
     * @param clazz {@link Class}
     * @param <T>   type
     * @return T
     */
    public static <T> T getBean(String name, Class<T> clazz)
    {
        return getApplicationContext().getBean(name, clazz);
    }
}

